# encoding:utf-8
"""

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane on 10/11/2025
"""
from datetime import datetime
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client

from project.lib.common import qcos_config


def convert_datetime(time_str):
    """
    :param time_str:
    :return:
    """
    utc_time = datetime.fromisoformat(time_str.replace('Z', '+00:00'))
    china_time = utc_time.astimezone()

    return china_time


class QCOSUtil(object):
    """ 腾讯COS 工具类
    """
    @staticmethod
    def generate_play_url(key: str):
        """ 生成播放链接
        :return:
        """
        config = CosConfig(Region=qcos_config.region, SecretId=qcos_config.secret_id, SecretKey=qcos_config.secret_key)
        client = CosS3Client(config)

        url = client.get_presigned_url(
            Bucket=qcos_config.bucket,
            Key=key,
            Params={
                'response-content-disposition': 'inline',  # 关键参数
                'response-cache-control': 'public, max-age=3600'
            },
            Method='GET',
            Expired=3600  # URL有效期（秒）
        )

        return url

    @staticmethod
    def get_files(prefix='', suffix='.mp4'):
        """ 腾讯云取得文件列表
        :return:
        """
        config = CosConfig(Region=qcos_config.region, SecretId=qcos_config.secret_id, SecretKey=qcos_config.secret_key)
        client = CosS3Client(config)

        response = client.list_objects(
            Bucket='lane-1343136304',
            Prefix=prefix
        )
        contents = response.get('Contents', [])

        contents.sort(key=lambda x: x['LastModified'], reverse=True)

        files = [
            {
                'name': v['Key'],
                'last_time': convert_datetime(v['LastModified']).strftime('%Y-%m-%d %H:%M:%S'),
                'url': f'{qcos_config.host}/{v["Key"]}'
            } for v in contents if v['Key'].endswith(suffix)
        ]

        return files


if __name__ == "__main__":
    """
    """
    records = QCOSUtil.get_files()
    for v in records:
        print(v)

